package me.shibor.study.servlet;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.Date;
import java.util.Enumeration;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


/**
 * 
 * 请求头信息
 * 相应头信息
 * @author shibor
 *
 */
@WebServlet("/HeadServlet")
public class HeadServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

    public HeadServlet() {
        super();
    }

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		//请求头显示
		Enumeration<String> enums = request.getHeaderNames();
		System.out.println("request header");
		while(enums.hasMoreElements()){
			String name = enums.nextElement();
			String value = request.getHeader(name);
			System.out.println(name + ":  " + value);
		}
		System.out.println("#################");
		
		//响应头
		//test1(response);
		
		test2(response);
		
		//test3(response);
		
	}
	
	/**
	 * 响应头处理，返回页面
	 * @param response
	 * @throws IOException 
	 */
	private void test1(HttpServletResponse response) throws IOException {
		
		//response.setHeader("refresh", "1");
		response.setContentType("text/html;charset=gbk");
		PrintWriter out = response.getWriter();
		out.println("<!DOCTYPE HTML>");
		out.println("<HTML>");
		out.println("<head><title>a servlet title</title></head>");
		out.println("<body>time now :");
		out.println(new Date().toString());
		out.println("</body>");
		out.println("</html>");
		out.flush();
		out.close();
	}
	
	/**
	 * 响应头处理， 下载图片
	 * @param response
	 * @throws IOException 
	 */
	private void test2(HttpServletResponse response) throws IOException {
		//download jpg
		System.out.println("response head: ");
		response.setContentType("image/jpeg");
		InputStream in = this.getClass().getClassLoader().getResourceAsStream("Koala.jpg");
		int len = in.available();
		System.out.println(len);
		byte[] buffer = new byte[len];
		in.read(buffer);
		OutputStream out = response.getOutputStream();
		out.write(buffer);
		out.flush();
		//in.close();
		out.close();
	}

	/**
	 * 响应头处理， 下载excel
	 * @param response
	 * @throws IOException 
	 */
	private void test3(HttpServletResponse response) throws IOException {
		//download excel
		System.out.println("response head: ");
		response.setContentType("application/vnd.ms-excel");
		PrintWriter out = response.getWriter();
		out.println("\tQ1\tQ2\tQ3\tQ4\tTotal");
		out.println("Apples\t78\t87\t92\t29\t=SUM(B2:E2)");
		out.println("Oranges\t77\t86\t93\t30\t=SUM(B3:E3)");
	}
	
}
